<?php

namespace app\store\service;

use think\facade\Db;

class IntegralSettingService
{
    public static function saveBaseSetting($data)
    {
        $store_id = session('store_id');
        if (!empty($data['id'])) {
            $result = Db::name('integral_setting')->where('id',$data['id'])->update([
                'store_id' => $store_id,
                'give_integral_scale' => $data['give_integral_scale'],
                'integral_desc' => $data['integral_desc'],
                'is_sign_in' => $data['is_sign_in'],
                'sign_in_integral' => $data['sign_in_integral'],
                'sign_in_config' => $data['sign_in_config'],
                'integral_gold_scale' => $data['integral_gold_scale'],
                'gold_balance_scale' => $data['gold_balance_scale'],
                'gold_desc' => $data['gold_desc'],
            ]);
            return  $result;
        }

        $result = Db::name('integral_setting')->insert([
            'store_id' => $store_id,
            'give_integral_scale' => $data['give_integral_scale'],
            'integral_desc' => $data['integral_desc'],
            'is_sign_in' => $data['is_sign_in'],
            'sign_in_integral' => $data['sign_in_integral'],
            'sign_in_config' => $data['sign_in_config'],
            'integral_gold_scale' => $data['integral_gold_scale'],
            'gold_balance_scale' => $data['gold_balance_scale'],
            'gold_desc' => $data['gold_desc'],
        ]);

        return $result;
    }

    public static function findBaseSetting()
    {
        $store_id = session('store_id');
        $baseConfig = Db::name('integral_setting')->withAttr('sign_in_config',function ($value){
                if (empty($value)){
                    return  [];
                }
                $config = json_decode($value,true);

                $sign_in_config = [];
                $i = 0;
                foreach ($config as $k => $v){
                    $sign_in_config[$i]['sign_in_day'] = $k;
                    $sign_in_config[$i]['give_integral'] = $v['give_integral'];
                    $sign_in_config[$i]['coupon_info'] = json_encode($v['coupon_info']);
                }

                return  $sign_in_config;

        })->where('store_id',$store_id)->find();

        return $baseConfig;
    }

    public static function formatSignInConfig($sign_in_config)
    {
        $config = [];
        foreach ($sign_in_config as $v){
            $config[$v['sign_in_day']]['give_integral'] = $v['give_integral'];
            $config[$v['sign_in_day']]['coupon_info'] = $v['coupon_info'];
        }

        return json_encode($config);
    }

}